$().ready(function () {
    validateRule();
    var money = $("#money").val();
    $("#topDuration").change(function () {
        var days = $(this).val();
        $("#allMoney").html(new Number(money * days).toFixed(2) + '元');
        $("#payShow").show()
    })
});

$.validator.setDefaults({
    submitHandler: function () {
        save();
    }
});

function save() {
    $.ajax({
        cache: true,
        type: "POST",
        url: "/jzApi/orgOrder/saveOrder",
        data: $('#signupForm').serialize(),// 你的formid
        async: false,
        error: function (request) {
            parent.layer.alert("Connection error");
        },
        success: function (res) {
            if (res.code == 0) {
                $.ajax({
                    type: "POST",
                    url: "/jzApi/orgOrder/wxPay",
                    data: {
                        orderId: res.data.orderId,
                        type: 0,
                        topDuration: res.data.topDuration,
                        residues: '',
                        body: '置顶费用',
                        trade_type: 'NATIVE'
                    },
                    success: function (data) {
                        if (data.code == 0) {
                            $("#img").attr("src", data.data.wx.data.code_url);
                            layer.open({
                                type: 1,
                                title: '扫码支付',
                                area: ['520px', '520px'],
                                content: $("#isTop") // iframe的url
                            });
                            monitor(res.data.orderId);
                        }

                    }
                })
            } else {
                layer.alert(res.msg)
            }

        }
    });
}

var timer = null;

function monitor(id) {
    timer = window.setInterval(function () {
        queryWxPay(id)
    }, 3000)
}

//轮询是否支付成功
function queryWxPay(id) {
    $.ajax({
        url: "/jzApi/orgOrder/selOrderState",
        data: {
            id: id
        },
        success: function (data) {
            if (data.data == 0) {
                window.clearInterval(timer);
                $("#img").attr("src", '/img/wxsuccess.png');
                layer.closeAll();
                var index = parent.layer.getFrameIndex(window.name); // 获取窗口索引
                parent.layer.close(index);
            }
        }
    });
}

function validateRule() {
    var icon = "<i class='fa fa-times-circle'></i> ";
    $("#signupForm").validate({
        rules: {
            orgId: {
                required: true
            },
            topDuration: {
                required: true,
                positiveInteger: true
            },
            startTime: {
                required: true
            }
        }
    })
}